<?PHP
/**
 * @file
 * Controls database operations on the dbDonation table.
 *
 * Copyright 2011 by Matt Edmonds This program is part of DONATE.
 * DONATE is free software.  It comes with absolutely no warranty.
 * You can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
 *
 * @version 3/9/11
 * @author Matt Edmonds
 */
include_once('dbConnect.php');
include_once('../model/Donation.php');


Class dbDonation{

	/**
	 * Creates the table corresponding to this database controller.
	 * @return true if MySQL server does not report any error. Otherwise,
	 * prints out the error and returns false.
	 */
	static function createTable() {

		$query =("CREATE TABLE donation (
            donationID   INT  NOT NULL AUTO_INCREMENT ,
            donationDate DATE NOT NULL ,
  donorID      INT  NULL ,
  eventID      INT  NULL ,
  CONSTRAINT pk_donation PRIMARY KEY (donationID),
  CONSTRAINT fk_donor_donation FOREIGN KEY (donorID)
	REFERENCES donor (donorID)ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT fk_event_donation FOREIGN KEY (eventID)
	REFERENCES event (eventID)ON DELETE CASCADE ON UPDATE CASCADE
  );
  ");

		connect();
		$result = mysql_query($query);
		echo mysql_error();
		mysql_close();
		if ($result == false) {
			return false;
		}

		//Previous query was successful.
		return true;
	}


	/**
	 * Retrieves a DonationID from the Donation table
	 *
	 * @param Donation $v The donationId to be searched.
	 *
	 * @return true if the query is successful.
	 */

	function getDonationID($v) {
		$result = mysql_query("SELECT donationID FROM donate WHERE
                donationID='$v'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}



	/**
	 * Retrieves a DonationDate from the Donation table
	 *
	 * @param Donation $v The donationId to be searched.
	 *
	 * @return true if the query is successful.
	 */
	function getDonationDate($v) {
		$query = "SELECT donationDate FROM Donation WHERE donationID='$v'";
		connect();
		$result = mysql_query($query);
		mysql_close();
		if ($result == false) {
			echo mysql_error( );
			return false;
		}
		//Query was successful.
		return $result;
	}


	/**
	 * Retrieves a DonorID from the Donation table
	 *
	 * @param Donation $v The donationId to be searched.
	 *
	 * @return true if the query is successful.
	 */
	function getDonorID($v) {
		$query = "SELECT donorID FROM Donation WHERE donationID='$v'";
		connect();
		$result = mysql_query($query);
		mysql_close();
		if ($result == false) {
			echo mysql_error( );
			return false;
		}
		//Query was successful.
		return $result;
	}

	/**
	 * Retrieves an EventID from the Donation table
	 *
	 * @param Donation $v The donationId to be searched.
	 *
	 * @return true if the query is successful.
	 */
	function getEventID($v) {
		$query = "SELECT eventID FROM Donation WHERE donationID='$v'";
		connect();
		$result = mysql_query($query);
		mysql_close();
		if ($result == false) {
			echo mysql_error( );
			return false;
		}
		//Query was successful.
		return $result;
	}


	static function addDonationByFields($donationDate, $donorID, $eventID, &$id)
	{
		$d = new Donation($donationDate, $donorID, $eventID);

		$result = dbDonation::addDonation($d, $id);
		if ($result == false) {
			die ("Donation could not be updated with specified information.<br />");
		}
	}


	/**
	 * Inserts data in the Donation table.
	 *
	 * @param Donation $v The data to be inserted. It has values for all the columns
	 * in the table, except for the primary key value, which is of type
	 * auto-increment. It is assumed that the data does not exist in the table.
	 *
	 * @return true if the query is successful.
	 */

	static function addDonation($v, &$id) {
		if (!$v instanceof Donation) {
			echo ("Invalid arguement insertInto ( ) function<br />");
			return false;
		}
		//Compose the INSERT INTO query srting. Primary key value is missing.
		//Database server automatically generates a unique ID for the primary Key.
		$query = sprintf("INSERT INTO donation VALUES(null, '%s', %d, %d)",
		$v->getDonationDate(),
		$v->getDonorID(),
		$v->getEventID()
		);
		connect( );
		$result = mysql_query($query);
		//printf("Donation added has id %d\n<br />", mysql_insert_id());
		$id = mysql_insert_id( );
		mysql_close( );
		if ($result == false) {
			echo mysql_error();
			return false;
		}
		//query was successful.
		return true;
	}

	static function verifyInsertedDonation($id)
	{
		$output = "";
		$error = dbDonation::getAllByID($id, $output);
		if ($error == true) {
			printf("%s<br />", $output);
		}
		else {
			$ind = new Donation($output['donationDate'], $output['donorID'], $output['eventID']);
			printf("Inserted: Donation with ID=%d has %s.<br />", $id, $ind->printAllAttributes( ));
		}
	}

	/**
	 * Deletes data from the Donation table.
	 *
	 * @param Donation $x The data to be deleted. It has values for all the columns
	 * in the table, including primary key value.
	 *
	 * @return true if the query is successful.
	 */
	function deleteDonation($v) {
		if (!$x instanceof Donation) {
			echo ("Invalid argument deleteDonation( ) function<br />");
			return false;
		}
		$i = $v->getDonationID();
		$query = sprintf ("DELETE FROM donation WHERE donationID='$i',$v->getDonationID");
		connect( );
		$result = mysql_query($query);
		mysql_close( );
		if ($result == false) {
			echo mysql_error( );
			return false;
		}

		//Query was successful.
		return true;

	}

	public static function getAllByID($id, &$output) {
		$query = sprintf("SELECT donationDate, donorID, eventID FROM donation WHERE donationID=%d",
		$id);
		// printf("->Query: %s<br />", $query);

		connect( );
		$result = mysql_query($query);
		mysql_close( );

		if ($result == false) {
			$output = sprintf("%s", mysql_error());
			return false;
		}
		//process result and print out warning or attribute values
		return dbDonation::checkForOneInstance($result, $id, $output);
	}

	private static function checkForOneInstance($result, $id, &$output)
	{
		//Local variables are initialized.
		//Think positively about what this checking returns :-) and set $errorStatus
		//to initial value false
		$errorStatus = false;

		$howMany = mysql_num_rows($result);
		// printf("-->Found %d instance(s) for donorID=%d.<br />", $howMany, $id);
		switch ($howMany) {
			case 0:
				$output = sprintf("No donation instance with ID=%d was found.",
				$id);
        $errorStatus = true;
        break;
      case 1:
        //mysql_fetch( ) DOES NOT return primary key values!
        $output = mysql_fetch_assoc($result);
        $errorStatus = false;
        break;
      default:
        $output = sprintf("There are multiple donation instances 
                           with ID=%d.", $id);
        $errorStatus = true;
        break;
    }
    return $errorStatus;
  }
	
}